<template>
    <div class="common-page page-corp-company-products" v-loading.fullscreen="loading">
        <div class="common-page__head">
            <comp-paths class="route" :paths="['/corp', '/corp/companys', '/corp/company?companyId=' + companyId]"></comp-paths>
            <div class="title" v-if="company">
                <div class="text">{{ company.name }}</div>
                <el-button type="plain" size="small" icon="el-icon-plus" @click="addProduct()" v-if="self">添加产品</el-button>
            </div>
            <div class="title" v-else></div>
        </div>
        <comp-tabs class="common-page__head" :tabs="['/corp/company?companyId=' + companyId, '/corp/company/orders?companyId=' + companyId, $route.fullPath, '/corp/company/demands?companyId=' + companyId, '/corp/company/attendances?companyId=' + companyId]"></comp-tabs>
        <comp-company-products class="common-page__body" ref="list" :companyId="companyId" select link>
            <!-- <template #head="scope">
                <el-button type="plain" size="small" icon="el-icon-refresh" @click="search()">刷新列表</el-button>
            </template> -->
            <template #body="scope">
                <el-button type="primary" size="mini" @click.stop="setProduct('start', scope.data)" v-if="self">编辑</el-button>
                <el-button type="danger" size="mini" @click.stop="delProduct(scope.data)" v-if="self">删除</el-button>
            </template>
        </comp-company-products>
        <comp-dialog :title="product && product.id ? '保存产品' : '添加产品'" ref="product" @close="setProduct('end')">
            <el-form size="small" label-width="98px" style="margin-right: 20px" @submit.native.prevent v-if="product">
                <el-form-item label="产品图片：" required>
                    <img style="display: block; margin: 0 10px 10px 0; max-width: 120px; height: 60px; object-fit: cover" :src="product.avatar.short" v-if="product.avatar.id" />
                    <el-button type="plain" icon="el-icon-plus" @click="setProduct('upload-avatar')">{{ product.avatar ? "更换图片" : "选择图片" }}</el-button>
                </el-form-item>
                <el-form-item label="产品名称：" required>
                    <el-input ref="productName" v-model="product.name" style="width: 480px" placeholder="请输入" :maxlength="100" :readonly="loading" @change="setProduct('validate')"></el-input>
                </el-form-item>
                <el-form-item label="产品内容：" required>
                    <el-input type="textarea" v-model="product.desc" style="width: 480px" placeholder="请输入" :maxlength="1000" :rows="10" resize="none" :readonly="loading" @change="setProduct('validate')"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-check" @click="setProduct('submit')">{{ product.id ? "保存" : "添加" }}</el-button>
                    <el-button type="plain" icon="el-icon-close" @click="setProduct('end')">放弃</el-button>
                </el-form-item>
            </el-form>
        </comp-dialog>
    </div>
</template>

<script>
    import mixin from "../mixin";
    import { string, int, deepCopy, selectFile, cache } from "../util";
    export default {
        name: "page-corp-company-products",
        title: "产品信息",
        nodes: ["/menu/corp"],
        childs: [],
        mixins: [mixin],
        data: () => ({
            loading: false,
            companyId: "",
            company: null,
            product: null,
            self: false,
        }),
        methods: {
            search() {
                if (this.loading) return;
                this.$nextTick(() => this.$refs.list.init());
            },
            addProduct() {
                if (this.loading) return;
                let company = this.company;
                let product = this.plugins.user.formatProduct();
                product.company.id = company.id;
                this.setProduct("start", product);
            },
            setProduct(action, data) {
                if (this.loading) return;
                let product = this.product;
                if (!action || action === "start") {
                    this.product = deepCopy(data);
                    this.setProduct("validate");
                    this.$refs.product.init();
                    this.$nextTick(() => this.$refs.productName.focus());
                } else if (action === "validate") {
                    let form = product;
                    let error = "";
                    error = error || (form.avatar.id ? "" : "请先上传产品图片！");
                    form.name = string(form.name).trim();
                    error = error || (form.name ? "" : "请先输入产品名称！");
                    form.desc = string(form.desc);
                    error = error || (form.desc ? "" : "请先输入产品内容！");
                    if (data) this.plugins.modal.toast(error, "error");
                    return !error;
                } else if (action === "upload-avatar") {
                    if (!data) return selectFile("image/*").then((file) => {
                        if (file.size > 5 * 1048576) this.plugins.modal.toast("图片过大，不能大于5MB哦！请重新选择。", "error");
                        else this.setProduct(action, file);
                    });
                    let timer = null;
                    let progress = (event) => timer = clearTimeout(timer) || setTimeout(() => this.plugins.modal.toast("上传进度：" + event.percent + "%", "info"), 200);
                    this.loading = true;
                    this.plugins.user.uploadFile(data, "image", progress).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            product.avatar = res.data;
                            this.setProduct("validate");
                        } else {
                            this.plugins.modal.alert("图片上传失败", res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "submit") {
                    if (!this.setProduct("validate", true)) return;
                    else this.loading = true;
                    if (product.id) this.plugins.user.setProduct(product).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.toast("保存成功！", "success");
                            this.setProduct("end");
                            this.search();
                        } else {
                            this.plugins.modal.alert("保存失败", res.code + "：" + res.msg, "error");
                        }
                    });
                    else this.plugins.user.addProduct(product).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.toast("添加成功！", "success");
                            this.setProduct("end");
                            this.search();
                        } else {
                            this.plugins.modal.alert("添加失败", res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "end") {
                    this.$refs.product.close();
                }
            },
            delProduct(product) {
                if (this.loading) return;
                this.plugins.modal.alert("删除确认", "确定删除该产品吗？", "warning", ["确定删除", "再想想"]).then((ok) => {
                    if (!ok) return;
                    this.loading = true;
                    this.plugins.user.delProduct(product).then((res) => {
                        this.loading = false;
                        if (res.code === -1) return;
                        if (res.code === 0) {
                            this.plugins.modal.toast("删除成功！", "success");
                            this.search();
                        } else {
                            this.plugins.modal.alert("删除失败：", res.code + "：" + res.msg, "error");
                        }
                    });
                });
            },
            destroy() {
                if (this.loading) return;
                return true;
            },
            init() {
                if (this.loading) return;
                let query = this.$route.query;
                let company = null;
                this.loading = true;
                this.companyId = query.companyId;
                this.company = cache(query.companyId);
                this.$root.$refs.navbar.init();
                this.plugins.user.call(async () => {
                    let res = await this.plugins.user.init();
                    if (res.code === 0) { }
                    return res;
                }, async () => {
                    if (this.access(this.$route.name)) return { code: 0 };
                    return this.env.xhrErrors.find((error) => error.code === 4);
                }, async () => {
                    let res = await this.plugins.user.getCompany(query.companyId);
                    if (res.code === 0) company = res.data;
                    return res;
                }).then((res) => {
                    this.loading = false;
                    this.$root.$refs.navbar.init();
                    if (res.code === 0) {
                        this.company = cache(query.companyId, company);
                        this.self = this.company.depts.some((dept) => this.profile.depments.some((depment) => depment.dept.id === dept.id));
                        this.search();
                    } else if (res.code === 2) {
                        this.$root.$refs.navbar.login();
                    } else {
                        this.plugins.modal.alert("页面加载失败", res.code + "：" + res.msg, "error").then(() => this.$router.replace("/corp/companys"));
                    }
                });
            },
        },
    };
</script>

<style lang="scss">
    .page-corp-company-products {
        overflow: hidden;
    }
</style>